<template>
  <!-- 弹框 dom -->
  <div id="popup" class="ol-popup" ref="mapContent" v-html="mapText" @click="onClickHandler"></div>
  <el-dialog v-model="isShowHotParkPointManage"
             :direction="direction"
             draggable
             top="80px"
             :modal="false"
             style="position: absolute;left: 200px;width:24%;">
    <template #title>
      <h2>停车区域管理</h2>
    </template>
    <template #default>
      <div>
        <el-radio v-model="hotParkPointRadio" label='gj20201221' size="large"
        >厦门市思明区湖里区停车区域</el-radio>
      </div>
      <!-- 泰森多边形注释 -->
      <div class="teissenClass" style="margin: 30px;" v-show="isShowTeissenText">
        <ul class="teissenClassUl" style="margin: 30px">
          <li class="teissenClassLi" >
            <div style="background-color:rgba(241,75,37,0.5);width: 20px;height: 20px;margin:19px 19px 19px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin-left:10px;margin-bottom: auto;margin-top: auto;font-size:medium ">共享单车净流出区域</span>
          </li>
          <li class="teissenClassLi" >
            <div style="background-color:rgba(22,243,92,0.5);width: 20px;height: 20px;margin:19px 19px 19px 0px"></div>
            <span class="PolygonStyle_fillType_05" style="margin-left:10px;margin-bottom: auto;margin-top: auto;font-size: medium">共享单车净流入区域</span>
          </li>
        </ul>
      </div>
    </template>
    <template #footer>
      <div style="flex: border-box">
        <el-button @click="hideRoadNet">显示/隐藏</el-button>
        <el-button @click="getxmTeissenData" v-show="isShowTeissen">泰森多边形</el-button>
        <el-button type="primary" @click="getxmRoadData">获取数据</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessageBox } from 'element-plus'
import "../pages/Map.vue";
import { ref, reactive, toRefs} from 'vue'
import store from "../store/index.js";
import axios from "axios";
import Point from "ol/geom/Point"
import WKT from "ol/format/WKT";
import { Fill, Stroke, Style, Text , Circle, Icon} from "ol/style";
import {Cluster,Vector as VectorSource} from 'ol/source';
import {Vector as VectorLayer} from 'ol/layer';
import { showLoading, hideLoading } from '../store/loading.js'
import Feature from 'ol/feature';
import View from 'ol/View';
import {getCurrentInstance} from 'vue';
import Overlay from 'ol/Overlay'// 引入覆盖物模块
import 'ol/ol.css' // ol提供的css样式(必须引入)

//气泡弹出框
// 弹框
const overlay = ref(null) // 弹框实例
const mapContent = ref(null) // 弹框挂载的 dom 元素
const mapText = ref(null) // 弹框内容
//获取点击坐标
const clickPointX=ref(null)
const clickPointY=ref(null)
//初始化弹框图层
// 创建弹框
const createOverlay = () => {
  overlay.value = new Overlay({
    name:'停车点弹出框',
    element: mapContent.value, // 将弹框挂载在 dom 上
    autoPan: true, // 如果弹框显示不全则自动归位
    positioning: 'bottom-center', // 相对标点的实际位置
    stopEvent: false, // 冒泡
    autoPanAnimation: {
      duration: 300 // 地图移动速度
    }
  })
  store.state.map.addOverlay(overlay.value) // 将弹框添加到地图上
}

const isShowHotParkPointManage = ref(false)

const direction = ref('rtl')
const hotParkPointRadio = ref('gj20201221')
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure you want to close this?')
      .then(() => {
        done()
      })
      .catch(() => {
        // catch error
      })
}
/*HotParkPointManage与TopMenu传值*/
//TopMenu通过Home.vue传值
export interface ExposeType {
  getIsShowHopParkPointMsg:Function;
}
//将TopMenu中的isshowBikeTrace值传入
const  getIsShowHopParkPointMsg = (val:boolean) => {
  isShowHotParkPointManage.value = val
  console.log('val2',val)
}
//将值暴露
defineExpose({
  getIsShowHopParkPointMsg
})

/*HotParkPointManage与HotParkPointManage传值*/
//向TopMenu传值
//向父组件Home.vue传递isShowBikeTrace值为True的信息
const emit = defineEmits<{(e:'toFather',
                           isShowStreetPhoto:boolean,
                           pointx:number,
                           pointy:number
                           ):void}>()

const isShowStreetPhoto = () =>{
  emit('toFather',true,clickPointX.value,clickPointY.value)
  console.log('按下街景按钮',clickPointY.value,clickPointY.value)
}
//显示街景按钮
const onClickHandler = (e) => {
  //可以通过class类名来判断，也可以通过tagName来判断
  const classList = e.target.classList;
  //v-html里假如有一个渲染类名为test的元素button
  if(classList.contains("checkStreetPhotoBtn")){
    //点击事件执行的逻辑
    isShowStreetPhoto()
  }
  //或者使用tagName来判断,但是这里要确定tagName是否唯一，所以个人感觉还是使用classList判断
  // const tagName = e.target.tagName.toLowerCase()
  // if(tagName === "button"){ //点击事件执行的逻辑 }
}


//道路轨迹可视化
//初始化厦门road Vector&source
const xmParkPointVector=ref(null)
const xmParkPointSource=ref(null)
const parkFeature=ref(null)
const parkFeatureCube=ref([])
const isGetParkPointData=ref(false)
//控制路网图层显示与隐藏
const isShowParkPoint=ref(true)
xmParkPointSource.value=new VectorSource({})
xmParkPointVector.value =new VectorLayer({
  name:'热门停车区域',
  source: xmParkPointSource.value,
  style: new Style({
    fill: new Fill({
      color: 'rgba(241,236,236,0.5)'
    }),
    stroke: new Stroke({
      color: 'rgb(102,129,245)',
      width: 1.1,
    }),
  })
})

//显示/隐藏路网图层
const hideRoadNet=()=>{
  if(isShowParkPoint.value){
    //隐藏
    xmParkPointVector.value.setVisible(false)
    isShowParkPoint.value=!isShowParkPoint.value
  }else{
    //显示
    xmParkPointVector.value.setVisible(true)
    isShowParkPoint.value=!isShowParkPoint.value
  }
}
//获取后台路网数据
const getxmRoadData=()=> {
  //展示Loading
  showLoading()
  //控制Teisson按钮显示与隐藏
  isShowTeissen.value=true;
  axios.get(store.state.dbApi + '/xmParkPoint').then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetParkPointData.value)
    {//已获取数据，清空变量
      xmParkPointSource.value.clear()
      parkFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmParkPointVector.value)
      //获取图层名字
      console.log(xmParkPointVector.value.get('name'))
      store.state.checkDiyLayerList.push(xmParkPointVector.value.get('name'))
      //激活地图点击事件
      traceCountMsgEvent()
      //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      createOverlay()
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      parkFeature.value=new WKT().readFeature(getData[i]['multipolygon'])
      //设置属性
      parkFeature.value.setProperties({
        name:'停车区域',
        id:getData[i]['id'],
        roadName:getData[i]['road_name'],
        centerX:getData[i]['centerx'],
        centerY:getData[i]['centery'],
        bikeRemain:getData[i]['bike_remain'],
      })
      parkFeatureCube.value.push(parkFeature.value)
    }
    isGetParkPointData.value=true
    //将线级加载到图源中
    //隐藏Loading
    hideLoading()
    xmParkPointSource.value.addFeatures( parkFeatureCube.value)
  })
}

//地图点击事件
const traceCountMsgEvent=()=>{
  let key=store.state.map.on("click", (e) =>{
    // console.log(e);
    let feature = store.state.map.forEachFeatureAtPixel(
        e.pixel,
        (feature, layer) => {
          return feature;
        }
    );
    //清空点击点数据
    if (feature &&feature.get('name')=='停车区域') {
      clickPointX.value=feature.get('centerX');
      clickPointY.value=feature.get('centerY');
      console.log( clickPointX.value,clickPointY.value,feature.get('centerX'),feature.get('centerY'))
      // 弹框内容
      mapText.value = "<ul>"+'<li>id：'+feature.get('id')+'</li>'+
          '<li>所在路段：'+feature.get('roadName')+'</li>'+
          '<li>单车留存量：'+parseInt(feature.get('bikeRemain'))+'辆'+'</li>'+
          '<li>停车区域中心点：'+feature.get('centerX').toFixed(9)+','+feature.get('centerY').toFixed(9)+'</li>'+
          "</ul>"+'<button class="checkStreetPhotoBtn">查看街景</button>'
      // 把overlay 显示到指定的坐标位置
      overlay.value.setPosition(e.coordinate)
    }
    else if(feature &&feature.get('name')=='Teissen'){
      // 弹框内容
      mapText.value = "<ul>"+'<li>id：'+feature.get('id')+'</li>'+
          '<li>区域面积：'+feature.get('area')+'平方千米'+'</li>'+
          '<li>单车流出：'+feature.get('o_count')+'辆'+'</li>'+
          '<li>单车流入：'+feature.get('d_count')+'辆'+'</li>'+
          '<li>单车留存量：'+feature.get('bikeRemain')+'辆'+'</li>'+
          '<li>点击区域位置：'+e.coordinate[0].toFixed(9)+','+e.coordinate[1].toFixed(9)+'</li>'+
          "</ul>"
      // 把overlay 显示到指定的坐标位置
      overlay.value.setPosition(e.coordinate)
    }
    else {
      // 弹框关闭
      console.log('弹框关闭')
      closeMapPopup()
    }
   // store.state.map.un(key.type, key.listener)
  })
}
//关闭弹框
const closeMapPopup = () => {
  overlay.value.setPosition(undefined)
}

/*泰森多边形*/
//变量可视化
const xmTeissenVector=ref(null)
const xmTeissenSource=ref(null)
const teissenFeature=ref(null)
const teissenFeatureCube=ref([])
const isGetTeissenData=ref(false)
//控制Teisson显示与隐藏
const isShowTeissen=ref(false)
//控制Teissen文本注释
const isShowTeissenText=ref(false)
xmTeissenSource.value=new VectorSource({})
xmTeissenVector.value =new VectorLayer({
  name:'泰森多边形',
  source: xmTeissenSource.value,
  style:function (feature){

   let input= 'rgba(22,243,92,0.5)'
   let output='rgba(241,75,37,0.5)'
   let _color=input
    if(feature.get('bikeRemain')<0){
      _color=output
    }
   return  new Style({
      fill: new Fill({
        color: _color
      }),
      stroke: new Stroke({
        color: 'rgb(0,0,0)',
        width: 1,
      }),
    })
  }
})

//获取泰森多边形
const getxmTeissenData=()=> {
  //展示Loading
  showLoading()
  //控制Teisson文本注释显示与隐藏
  isShowTeissenText.value=true;
  axios.get(store.state.dbApi + '/tession').then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetTeissenData.value)
    {//已获取数据，清空变量
      xmTeissenSource.value.clear()
      teissenFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmTeissenVector.value)
      //获取图层名字
      console.log(xmTeissenVector.value.get('name'))
      store.state.checkDiyLayerList.push(xmTeissenVector.value.get('name'))
      //激活地图点击事件
      //traceCountMsgEvent()
      //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      //createOverlay()
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      teissenFeature.value=new WKT().readFeature(getData[i]['multipolygon'])
      //设置属性
      teissenFeature.value.setProperties({
        name:'Teissen',
        id:getData[i]['gid'],
        area:getData[i]['area'],
        o_count:getData[i]['o_count'],
        d_count:getData[i]['d_count'],
        bikeRemain:getData[i]['remain'],
        density:getData[i]['density'],
      })
      teissenFeatureCube.value.push(teissenFeature.value)
    }
    isGetTeissenData.value=true
    //将线级加载到图源中
    //隐藏Loading
    hideLoading()
    xmTeissenSource.value.addFeatures(teissenFeatureCube.value)
  })
}

</script>

<style>
.teissenClassLi{
  display: flex;
}
.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0,0,0,0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 320px;
  /*隐藏*/
  z-index:-100
}
.ol-popup:after, .ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}
.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}
/*ul li设计*/
.ol-popup li{
  list-style-type :none;
  margin-left: auto;
  text-align: initial;
  font-size: initial;
  color: #504f4f;
}
</style>